import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:merchants/models/sku.dart';
import 'package:merchants/services/base-service.dart';

class SkuService extends BaseService {
  SkuService({required super.ref});

  Future<List<Sku>> getList({required String spuId}) async {
    final response = await get(
      '/admin/sku/get-list',
      queryParams: {'spuId': spuId},
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '获取Sku信息失败');
        }
        return json;
      },
    );
    final List<dynamic> records = response['data'] as List<dynamic>;
    return records
        .map((json) => Sku.fromJson(json as Map<String, dynamic>))
        .toList();
  }

  // 添加
  Future<String> create({required Sku sku, String? spuId}) async {
    // 构造 data 对象
    final Map<String, dynamic> skuData = {
      ...sku.toJson(), // 展开所有字段
    };

    // 如果 spuId 非空，确保 spu 格式正确
    if (spuId != null) {
      skuData['spu'] = {'_id': spuId};
    }

    return await post<String>(
      '/admin/sku/create',
      body: {'data': skuData},
      parser: (json) {
        if (json['success'] != true || json['data']?['id'] == null) {
          throw ApiException(json['message'] ?? 'Failed to create SKU');
        }
        return json['data']['id'] as String;
      },
    );
  }

  Future<void> updateSku({required Sku sku}) async {
    if (sku.id == null) {
      throw ApiException('SKU ID cannot be null for update');
    }

    await put<void>(
      '/admin/sku/update/${sku.id}',
      body: {'data': sku.toJson()},
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? 'Failed to update SKU');
        }
      },
    );
  }

  Future<void> deleteSku({required String skuId}) async {
    await delete<void>(
      '/admin/sku/$skuId',
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? 'Failed to delete SKU');
        }
      },
    );
  }

  Future<Sku> getSku({required String skuId}) async {
    return await get<Sku>(
      '/admin/sku/$skuId',
      parser: (json) {
        if (json['success'] != true || json['data'] == null) {
          throw ApiException(json['message'] ?? 'Failed to fetch SKU');
        }
        return Sku.fromJson(json['data'] as Map<String, dynamic>);
      },
    );
  }
}
